package com.sky.common.util;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 状态码管理器
 */
public class StatusCodeManager {

	private static Properties statusCodes = new Properties();// code码key,描述值

	private static Log logger = LogFactory.getLog(StatusCodeManager.class);

	static {

		init("config","statuscode.xml");
	}

	
	public static String getCodeMsg(String statusCode) {

		return statusCodes.getProperty(statusCode);

	}
	
	@SuppressWarnings("unchecked")
	public static void init(String path,final String fileName) {

		InputStream in = null;

		try {

			// in = StatusCodeManager.class.getResourceAsStream(filePath);
			in = findFileInput(path, fileName);
			
			if(in == null){
				
				logger.info(LogFormat.formatMsg("StatusCodeManager.init", "StatusCodeManager",
						"find file input is null.please check path."));
				return;
			}
			
			SAXReader reader = new SAXReader();

			Document document = reader.read(in);

			Element element = document.getRootElement();

			List<Element> elements = element.elements("statuscode");
			
			Properties tempStatusCode = new Properties();

			for (Element oneElement : elements) {

				tempStatusCode.setProperty(oneElement.attributeValue("code"), oneElement.attributeValue("msg"));

			}

			logger.info(LogFormat.formatMsg("StatusCodeManager.init", "StatusCodeManager",
					"load properties success,size = " + tempStatusCode.size()));
			
			statusCodes = tempStatusCode;

		} catch (Exception e) {

			logger.error(LogFormat.formatMsg("StatusCodeManager.init", "StatusCodeManager", "load properties failure"), e);

		} finally {

			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}

		}

	}

	private static InputStream findFileInput(String path,final String fileName) throws IOException {

		logger.info("path:" + path + ",file " + fileName);

		Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(path);

		InputStream in = null;

		while (dirs.hasMoreElements()) {

			URL url = dirs.nextElement();

			logger.info("protocol is " + url.getProtocol());

			if ("file".equals(url.getProtocol())) {

				String packagePath = URLDecoder.decode(url.getFile(), "UTF-8");
				File dir = new File(packagePath);
				// 如果不存在或者 也不是目录就直接返回
				if (!dir.exists() || !dir.isDirectory()) {
					// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
					continue;
				}

				File[] files = dir.listFiles(new FileFilter() {
					@Override
					public boolean accept(File pathname) {

						if (pathname.isFile() && pathname.getName().equals(fileName)) {

							return true;
						}
						return false;
					}
				});

				if (files != null && files.length > 0) {

					// System.out.println("files in size " + files.length);
					in = new FileInputStream(files[0]);
					break;
				}

			} else if ("jar".equals(url.getProtocol())) {
				// 获取jar
				JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
				// 从此jar包 得到一个枚举类
				JarEntry fileEntry = jar.getJarEntry(path + '/' + fileName);

				if (fileEntry != null) {

					in = jar.getInputStream(fileEntry);
					break;
				}
			}
		}

		return in;
	}

	public static void main(String[] args) {
		System.out.println(StatusCodeManager.getCodeMsg("999"));
	}

}
